package com.epoint.mobileoa.tools;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

/**
 * @author liyc
 * @time 2012-9-3 下午1:55:08
 * @annotation 解析帮助类
 */
public class XMLUtil {

	public static final String XMLTAG = "<?xml version=\"1.0\" encoding=\"utf-8\"?>";

	/**
	 * Dom通用解析类
	 * @param xml 列表xml字符串
	 * @param c 解析Model
	 * @return 返回存放Model实例的list对象
	 * @throws Exception
	 */
	public static ArrayList DomAnalysisCommon(String xml,Class<?> c)
	{
		try{
			Document document = DocumentHelper.parseText(XMLTAG + xml);
			ArrayList list = new ArrayList();
			Element root = document.getRootElement();
			List focs = root.elements();
			Object nc = c.newInstance();
			Field[] fields = nc.getClass().getDeclaredFields();
			int fLen = fields.length;
			for(int i=0;i<focs.size();i++)
			{
				Element foc = (Element) focs.get(i);
				nc = c.newInstance();
				for(int j = 0 ; j < fLen; j++) {
					String fieldName = fields[j].getName();
					if (foc.element(fieldName) != null){
						fields[j].set(nc,foc.elementText(fieldName));
					}
				}
				list.add(nc);
			}
			return list;
		}
		catch(Exception e)
		{
			e.printStackTrace();
			return null;
		}
	}
}
